<?php
/**
 * Service User
 * User: Administrator
 * Date: 2020/2/17 0017
 * Time: 下午 1:29
 */
namespace app\api\service\user;

use app\api\model\user\User as UserModels;

Class User{

    /**
     * 注册或绑定用户
     * @param string|NULL $unionid
     * @param string $openid
     * @param string $state 来源
     * @return mixed
     */
    public function binding( $unionid=NULL, string $openid, $state )
    {
        $field = $state.'_openid';
        $user = UserModels::openid(['field'=>$field,'openid'=>$openid])->findOrEmpty();
        if ( false === $user->isEmpty() ) { //如果存在
            if ( $unionid && !$user->unionid ) {
                $user->unionid = $unionid;
                if ( false === $user->save() ) {
                    return returnData([],'unionid绑定失败', 500);
                }
                $res = $user->toArray();
                $res['unionid'] = $unionid;
                return returnData($res, '绑定成功');
            }
        } else {
            if ( $unionid ) {
                $user = UserModels::unionid($unionid)->findOrEmpty();
                if ( false === $user->isEmpty() ) {
                    $user->$field = $openid;
                    if ( false === $user->save() ) {
                        return returnData([], 'openid绑定失败', 500);
                    }
                    $res = $user->toArray();
                    $res[$field] = $openid;
                    return returnData($res, '绑定成功');
                }
            }
            $create = UserModels::create([
                $field => $openid,
                'unionid' => $unionid
            ]);
            if ( false === $create->isEmpty() ) {
                return returnData($create->toArray(), '注册成功');
            }
            return returnData([], '注册失败', 500);
        }
        return returnData($user->toArray(), '用户已存在', 200);
    }

    /**
     * 更新或添加用户信息
     * @author zx
     * @date 2019-10-25
     * @return boolean
     */
    public function saveUserInfo(array $data, int $uid)
    {
        $userInfo = UserModels::get($uid);
        if ( NULL !== $userInfo ) {
            $userInfo->headimg_url = $data['headimg_url'];
            $userInfo->nickname = $data['nickname'];
            return $userInfo->save();
        }
        return false;
    }

}